import Taro from '@tarojs/taro';
import {getGlobalData} from "./globalData";

/**
 * 防抖函数
 * @param fn
 * @param delay
 * @returns {function(...[*]=)}
 */
let runFlagDebounce = true;
export function debounce(fn, delay){
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    if (runFlagDebounce) {
      fn.apply(this, args);
      runFlagDebounce = false;
    }
    timer = setTimeout(() => {
      runFlagDebounce = true;
    }, delay);
  };
};

/**
 * 延迟执行
 * @param {*} fn
 * @param {*} delay
 * @returns
 */
export function debounceDelay(fn, delay) {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);

    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone');
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 *
 * @param {Object} obj
 * @returns {Object}
 */
export function invertKeyValues(obj) {
  return Object.keys(obj).reduce((acc, key) => {
    acc[obj[key]] = key;
    return acc;
  }, {});
}

/**
 *
 * @param  {Array}           arr      The array to group items from
 * @param  {String|Function} criteria The criteria to group by
 * @return {Object}                   The grouped object
 */
export function groupBy(arr, criteria) {
  return arr.reduce(function (obj, item) {
    const key = typeof criteria === 'function' ? criteria(item) : item[criteria];

    if (!obj.hasOwnProperty(key)) {
      obj[key] = [];
    }

    obj[key].push(item);

    return obj;
  }, {});
}

/**
 *
 * @param {number} delay 毫秒
 */
export async function sleep(delay = 1000) {
  return new Promise((resolve) => {
    setTimeout(resolve, delay);
  });
}

/**
 * 判断是否存在底部的高度
 * @returns boolean
 */
export function hasBottomHeight() {
  let bottomHight = Taro.$bottomHight;
  if (Taro.$isH5 && window.history.length == 1 && Taro.$isIphoneX) {
    bottomHight = true;
  }

  return bottomHight;
}

/*
 * num [function] 传入的数字
 * decimal [number] 需要保留几位小数
 */
export function RoundNum(num, decimal = 2) {
	return Math.round(num * 10 ** decimal) / 10 ** decimal;
}

export function getRealPx(px){
  return getGlobalData('windowWidth')*px/750
}
